﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RRSimulator.BlobManager
{
    public class CookieMessageInspector : IClientMessageInspector
    {
        public CookieMessageInspector()
        {

        }

        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {

        }

        /// <summary>
        /// Attaches cookie to the outgoing message properties
        /// [The cookie needed to be stored in the Globals.Cookie property]
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,
            System.ServiceModel.IClientChannel channel)
        {
            if (string.IsNullOrEmpty(Globals.Cookie))
            {
                Console.WriteLine("No Cookie Information found! Please Authenticate.");
                return null;
            }

            HttpRequestMessageProperty requestMessageProperty = new HttpRequestMessageProperty();
            requestMessageProperty.Headers[HttpResponseHeader.SetCookie] = Globals.Cookie;
            request.Properties[HttpRequestMessageProperty.Name] = requestMessageProperty;

            return null;
        }
    }
}
